<template>
  <div id="app" class="app-container">
    <!-- 顶部搜索栏 -->
    <header class="search-bar">
      <!-- 用餐类型选择栏 -->
      <div class="meal-type-selector">
        <label for="mealType"></label>
        <select v-model="selectedMealType" id="mealType" class="meal-type-dropdown">
          <option value="早餐">早餐</option>
          <option value="午餐">午餐</option>
          <option value="晚餐">晚餐</option>
          <option value="加餐">加餐</option>
        </select>
      </div>
      <input v-model="searchQuery" class="search-input" placeholder="请输入食物名称" />
      <button @click="searchFoods" class="search-btn">搜索</button>
    </header>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧分类列表 -->
      <div class="category-list">
        <ul>
          <li v-for="category in categories" :key="category" :class="{ active: category === selectedCategory }"
            @click="changeCategory(category)">
            {{ category }}
          </li>
        </ul>
      </div>

      <!-- 右侧食物信息列表 -->
      <div class="food-list">
        <div class="food-item" v-for="food in filteredFoods" :key="food.id" @click="showDetails(food)">
          <!-- 添加图片 -->
          <img v-if="food.img_url" :src="food.img_url" alt="food-image" class="food-image" />
          <div class="food-info">
            <h3>{{ food.name }}</h3>
            <p>热量：{{ food.calories }} 千卡/{{ food.unit }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 食物详情弹窗 -->
    <div v-if="showDetail" class="detail-overlay" @click="hideDetails">
      <div class="detail-popup" @click.stop>
        <h2 class="popup-title">{{ selectedFood.name }}</h2>
        <p class="popup-info">热量：{{ selectedFood.calories }} 千卡/{{ selectedFood.unit }}</p>
        <p class="popup-info">蛋白质：{{ selectedFood.protein }} g/{{ selectedFood.unit }}</p>
        <p class="popup-info">脂肪：{{ selectedFood.fat }} g/{{ selectedFood.unit }}</p>
        <p class="popup-info">碳水化合物：{{ selectedFood.carbs }} g/{{ selectedFood.unit }}</p>

        <!-- 输入食物质量 -->
        <div class="quantity-container">
          <label for="quantity">请输入质量 (克)：</label>
          <input v-model="quantity" id="quantity" type="number" min="0" class="quantity-input" />
        </div>

        <!-- 显示计算后的营养成分 -->
        <div v-if="quantity > 0" class="calculated-nutrition">
          <p class="calculated-title">计算结果：</p>
          <p>热量：{{ nutrition.calories }} 千卡</p>
          <p>蛋白质：{{ nutrition.protein }} g</p>
          <p>脂肪：{{ nutrition.fat }} g</p>
          <p>碳水化合物：{{ nutrition.carbs }} g</p>
        </div>

        <!-- 记录时间的板块 -->
        <div class="record-time">
          <label>记录时间：</label>
          <uni-datetime-picker v-model="selectedTime" type="datetime" :start="startTime" :end="endTime"
            @change="onTimeChange"></uni-datetime-picker>
        </div>

        <div class="button-container">
          <button @click="saveRecord" class="calculate-btn">保存</button>
          <button @click="hideDetails" class="close-btn">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      mealTypes: ['早餐', '午餐', '晚餐', '加餐'],
      selectedMealType: '',
      categories: ['主食', '蔬菜水果', '肉蛋奶', '豆类坚果', '零食饮料', '组合餐', '其他'],
      selectedCategory: '主食',
      searchQuery: '',
      foods: [],
      showDetail: false,
      selectedFood: null,
      quantity: 0, // 新增字段：输入的食物质量
      nutrition: {},// 新增字段：记录计算的营养成分
    };
  },
  created() {
    // 设置默认时间范围
    const now = new Date();
    this.selectedTime = this.formatDateTime(now); // 默认选中当前时间
    this.startTime = this.formatDateTime(new Date(now.getFullYear() - 1, now.getMonth(), now.getDate()));
    this.endTime = this.formatDateTime(new Date(now.getFullYear() + 1, now.getMonth(), now.getDate()));
    // 使用 this.$route.query 获取 URL 查询参数
    const mealType = this.$route.query.mealType;
    console.log("mealType: ", mealType);

    if (mealType && this.mealTypes.includes(mealType)) {
      this.selectedMealType = mealType; // 设置默认选中的用餐类型
    } else {
      this.selectedMealType = '早餐'; // 如果没有传递参数，默认为早餐
    }

    this.fetchFoods(); // 组件加载时请求食物数据
  },
  computed: {
    filteredFoods() {
      // 根据搜索查询和选择的类别筛选食物
      return this.foods.filter(
        (food) =>
          food.category === this.selectedCategory &&
          food.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      );
    },
  },
  watch: {
    // 监控quantity的变化并实时更新营养计算
    quantity(newQuantity) {
      if (newQuantity > 0 && this.selectedFood) {
        this.calculateNutrition();
      }
    }
  },
  methods: {
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 切换分类
    changeCategory(category) {
      this.selectedCategory = category;
    },
    // 搜索食物
    searchFoods() {
      // 搜索会通过计算属性 filteredFoods 自动过滤
    },
    // 显示食物详情
    showDetails(food) {
      this.selectedFood = food;
      this.showDetail = true;
      this.quantity = 0; // 每次显示详情时清空质量输入框
      this.nutrition = {}; // 清空上一次计算的营养数据
    },
    // 隐藏食物详情
    hideDetails() {
      this.showDetail = false;
    },
    // 获取食物数据
    async fetchFoods() {
      try {
        const response = await fetch(`${this.$baseUrl}/calorie/getFoodsInfo`);
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const data = await response.json();
        // 确保数据是一个数组
        this.foods = Array.isArray(data) ? data : [];
      } catch (error) {
        console.error('获取食物数据失败:', error);
      }
    },
    calculateNutrition() {
      if (this.quantity <= 0) {
        alert('请输入有效的食物质量');
        return;
      }

      const food = this.selectedFood;
      // 计算热量和营养成分
      this.nutrition.calories = (food.calories * this.quantity) / parseFloat(food.unit);
      this.nutrition.protein = (food.protein * this.quantity) / parseFloat(food.unit);
      this.nutrition.fat = (food.fat * this.quantity) / parseFloat(food.unit);
      this.nutrition.carbs = (food.carbs * this.quantity) / parseFloat(food.unit);
    },
    saveRecord() {
      // 格式化时间函数（使用 ISO 标准格式）
      const formatDateTime = date => new Date(date).toISOString();

      // 构建记录数据
      const record = {
        food_name: this.selectedFood.name,
        meal_type: this.selectedMealType,
        entry_time: formatDateTime(this.selectedTime), // ISO 格式时间
        weight: this.quantity,
        calories: this.nutrition.calories,
        protein: this.nutrition.protein,
        fat: this.nutrition.fat,
        carbs: this.nutrition.carbs,
      };

      console.log('发送到后端的请求体:', JSON.stringify(record)); // 检查请求体

      // 发送保存记录请求到后端
      fetch(`${this.$baseUrl}/calorie/saveMealRecord`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Bearer ' + uni.getStorageSync('access_token'),
        },
        body: JSON.stringify(record),
      })
        .then(response => {
          if (!response.ok) {
            console.error('后端返回错误状态:', response.status);
            return response.json().then(errorData => {
              console.error('后端返回错误内容:', errorData);
              throw new Error(JSON.stringify(errorData));
            });
          }
          return response.json();
        })
        .then(data => {
          console.log('后端返回的数据:', data); // 检查后端返回的数据
          if (data.success) {
            console.log('记录保存到数据库成功:', data);

            // 确保跳转逻辑正常
            console.log('准备跳转到页面: /pages/index/calorie_intake');
            uni.navigateBack({
              delta: 1,
            });
            // 关闭弹窗
            this.showDetail = false;
          } else {
            console.error('保存记录失败:', data);
            alert('保存记录失败，请稍后重试');
          }
        })
        .catch(error => {
          console.error('保存记录失败:', error.message || error);
          alert(error.message || '保存记录失败，请稍后重试');
        });
    },
  },
};
</script>

<style scoped>
.app-container {
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.record-time {
  margin: 20px 0;
  font-size: 16px;
  color: #333;
}

.uni-datetime-picker {
  margin-top: 10px;
}

label {
  font-weight: bold;
}

.meal-type-selector {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 0px 10px 0px 0px;
  justify-content: center;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.meal-type-dropdown {
  padding: 4px 4px;
  font-size: 18px;
  border: none;
  border-radius: 5px;
  background-color: #f4f4f4;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.meal-type-dropdown:hover {
  background-color: #e0e0e0;
}

.search-bar {
  display: flex;
  justify-content: center;
  padding: 10px;
  background-color: #ffffff;
  width: 100%;
  border-bottom: 2px solid #ccc;
}

.search-input {
  flex-grow: 1;
  padding: 10px;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  max-width: 500px;
  background-color: #f9f9f9;
  transition: background-color 0.3s ease;
}

.search-input:focus {
  background-color: #fff;
  border-color: #4caf50;
  outline: none;
}

.search-btn {
  /* padding: 10px 20px; */
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  white-space: nowrap;
  align-self: center;
  margin-right: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s ease, box-shadow 0.3s ease;
}

.search-btn:hover {
  background-color: #45a049;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.main-content {
  display: flex;
  padding: 20px;
  gap: 20px;
}

.category-list {
  width: 32%;
  background-color: #ffffff;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.category-list ul {
  list-style-type: none;
  padding: 0px;
}

.category-list li {
  padding: 16px;
  cursor: pointer;
  font-size: 16px;
  border-radius: 5px;
  transition: background-color 0.3s ease;
  margin: 2px;
}

.category-list li.active {
  background-color: #4caf50;
  color: white;
}

.category-list li:hover {
  background-color: #e0e0e0;
}

.food-list {
  width: 100%;
  padding: 0px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.food-item {
  width: calc(33.33% - 20px);
  margin: 10px;
  padding: 15px;
  border: 1px solid #ccc;
  border-radius: 10px;
  cursor: pointer;
  background-color: #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s ease, box-shadow 0.3s ease;
}

.food-item:hover {
  background-color: #f4f4f4;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.food-info h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.food-info p {
  margin: 5px 0;
  color: #555;
}

.detail-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.detail-popup {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 12px;
  width: 90%;
  max-width: 500px;
  box-sizing: border-box;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.popup-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #4caf50;
}

.popup-info {
  font-size: 16px;
  margin-bottom: 8px;
  color: #555;
}

.quantity-container {
  margin: 20px 0;
}

.quantity-container label {
  font-size: 16px;
  margin-right: 10px;
  color: #555;
}

.quantity-input {
  padding: 0px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 5px;
  width: 100%;
  background-color: #f9f9f9;
  transition: background-color 0.3s ease;
}

.quantity-input:focus {
  background-color: #fff;
  border-color: #4caf50;
  outline: none;
}

.calculated-nutrition {
  margin-top: 20px;
}

.calculated-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #4caf50;
}

.button-container {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.calculate-btn,
.close-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease, box-shadow 0.3s ease;
}

.calculate-btn {
  background-color: #4caf50;
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.calculate-btn:hover {
  background-color: #45a049;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.close-btn {
  background-color: #f44336;
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.close-btn:hover {
  background-color: #e53935;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

/* 添加图片样式 */
.food-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 10px;
}
</style>